#include "videowidget.h"
#include <QPainter>
#include <QMutexLocker>
VideoWidget::VideoWidget(QWidget *parent)
    : QWidget{parent}
{
    setBackgroundRole(QPalette::Dark);//Dark
    //setAutoFillBackground(true);
}

VideoWidget::~VideoWidget()
{

}

void VideoWidget::setFrame(const QImage& frame)
{
    QMutexLocker locker(&m_mutex);
    m_currentFrame = QPixmap::fromImage(frame);
    update(); // 请求重绘

#if 0
    m_currentFrame = QPixmap::fromImage(QImage(frame));
    update(); // 请求重绘
#endif
}

void VideoWidget::clearFrame()
{
    QMutexLocker locker(&m_mutex);
    m_currentFrame = QPixmap(); // 清除当前帧数据
    update(); // 触发重绘
}

void VideoWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);

    QMutexLocker locker(&m_mutex);
    if (!m_currentFrame.isNull()) {
        // 缩放并居中显示
        QRect targetRect = QRect(0, 0, width(), height());
        QSize scaledSize = m_currentFrame.size().scaled(targetRect.size(), Qt::KeepAspectRatio);

        QRect centeredRect(
            targetRect.center().x() - scaledSize.width() / 2,
            targetRect.center().y() - scaledSize.height() / 2,
            scaledSize.width(),
            scaledSize.height()
        );

        painter.drawPixmap(centeredRect, m_currentFrame);
    }
    else {
        // 没有帧时显示提示文本
        painter.setPen(Qt::black); //black
        painter.drawText(rect(), Qt::AlignCenter, "视频已停止");
    }
}
